import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)
  const [command,setCommand] = useState([])

  function infixToPostfix(expression) {
    const output = [];
    const stack = [];
    const precedence = {
        '+': 1,
        '-': 1,
        '*': 2,
        '/': 2,
    };

    const tokens = expression.match(/\d+(\.\d+)?|[+\-*/()%]/g);

    for (const token of tokens) {
        if (!isNaN(token)) {
            output.push(token); // 如果是数字，直接加入输出
        } else if (token === '(') {
            stack.push(token); // 左括号直接压入栈
        } else if (token === ')') {
            while (stack.length && stack[stack.length - 1] !== '(') {
                output.push(stack.pop()); // 弹出直到遇到左括号
            }
            stack.pop(); // 弹出左括号
        } else {
            // 操作符
            while (stack.length && precedence[stack[stack.length - 1]] >= precedence[token]) {
                output.push(stack.pop()); // 弹出栈顶操作符
            }
            stack.push(token); // 将当前操作符压入栈中
        }
    }

    while (stack.length) {
        output.push(stack.pop()); // 将栈中的操作符弹出
    }

    return output.join(' ');
}
function evaluatePostfix(postfix) {
  const stack = [];  // 初始化一个栈

  // 将后缀表达式分割成单个元素
  const tokens = postfix.split(' ');

  // 遍历每个元素
  for (const token of tokens) {
      // 检查当前元素是否为数字
      if (!isNaN(token)) {
          stack.push(Number(token)); // 将数字转换为数字类型并压入栈中
      } else {
          // 如果是操作符，从栈中弹出两个操作数
          const b = stack.pop(); // 栈顶元素作为右操作数
          const a = stack.pop(); // 次顶元素作为左操作数

          // 根据操作符进行相应的计算
          switch (token) {
              case '+':
                  stack.push(a + b); // 加法
                  break;
              case '-':
                  stack.push(a - b); // 减法
                  break;
              case '*':
                  stack.push(a * b); // 乘法
                  break;
              case '/':
                  stack.push(a / b); // 除法
                  break;
              case '%':
                  stack.push(b / 100);//百分号
                  break
              default:
                  throw new Error(`Unknown operator: ${token}`); // 处理未知操作符
          }
      }
  }

  // 栈中的最后一个元素即为计算结果
  return stack[0];
}
function calculate(expression) {
  const postfix = infixToPostfix(expression);
  console.log(postfix);
  return evaluatePostfix(postfix);
}
  /**
   * 用栈这种数据结构
   * @param {*} c 
   * @returns 
   */
  const clickCommand = (c) => {
    
    if(c === '='){//计算结果
      console.log(command);  
      let result = calculate(command.join(''))
      setCommand([result])
      // let index = 0;
      // let _nums = [];
      // let _flags = []
      // command.forEach((e,i) => {
      //   if(e === '/' || e === '*' || e === '+' || e === '-' || e === ')' || e === '(' || e === '%'){
      //     let num = Number(command.slice(index,i).join(''));
      //     _nums.push(num);
      //     index = i + 1;
      //     _flags.push(e);
      //   }
      // })
      // let num = Number(command.slice(index,command.length).join(''));
      // _nums.push(num);
      // _nums = _nums.filter(e => e > 0);
      // console.log(_nums);
      // console.log(_flags);
      
       //假设我调换下顺序
      //  function _cal_sum(flags,nums){
      //   let f = flags;
      //   let n = nums;
      //   for(let i =0;i<f.length;i++){
      //     let _f = f[i]
      //     if(_f === '('){
            
      //     }else if(_f === ')'){

      //     }else if(_f === '/' || _f === '*'){

      //     }else if(f === '+' || _f === '-'){

      //     }
      //   }
      //   return _cal_sum
      //  }
    
      /**
       * 没有按照顺序来做
       */
      // let sum = _nums[0];
      // for(let i = 0;i<_flags.length;i++){
      //   let _f = _flags[i];
      //   if(_f === '*'){
      //     sum = sum * _nums[i+1]
      //   }else if(_f === '/'
      return;
    }
    if(c === 'CE'){//需要退一格
      command.pop();
      setCommand([...command])
      return
    }
    if(c === 'AC'){
      setCommand([])
      return
    }
    setCommand([...command,c])
  }
  const _str_commands = (commands) => {
    
    return commands.join('')
  }
  return (
    <>
        <p className='align-right h-15'>{command}</p>
        <table>
          <tbody>

          <tr>
            <td>
              <button onClick={() => clickCommand('(')}>(</button>
            </td>
            <td>
              <button onClick={() => clickCommand(')')}>)</button>
            </td>
            <td>
              <button onClick={() => clickCommand('%')}>%</button>
            </td>
            <td>
              <button style={{
                maxWidth:'45.11px',
                textAlign:'center',
                paddingLeft:'0.7em'
              }} onClick={() => clickCommand(command.length > 1 ? 'CE':'AC')}>{
                command.length > 1 ? 'CE':'AC'
              }</button>
            </td>
          </tr>
          <tr>
            <td>
              <button onClick={() => clickCommand('7')}>7</button>
            </td>
            <td>
              <button onClick={() => clickCommand('8')}>8</button>
            </td>
            <td>
              <button onClick={() => clickCommand('9')}>9</button>
            </td>
            <td>
              <button onClick={() => clickCommand('/')}>/</button>
            </td>
          </tr>
          <tr>
            <td>
              <button onClick={() => clickCommand('4')}>4</button>
            </td>
            <td>
              <button onClick={() => clickCommand('5')}>5</button>
            </td>
            <td>
              <button onClick={() => clickCommand('6')}>6</button>
            </td>
            <td>
              <button onClick={() => clickCommand('*')}>*</button>
            </td>
          </tr>
          <tr>
            <td>
              <button onClick={() => clickCommand('1')}>1</button>
            </td>
            <td>
              <button onClick={() => clickCommand('2')}>2</button>
            </td>
            <td>
              <button onClick={() => clickCommand('3')}>3</button>
            </td>
            <td>
              <button onClick={() => clickCommand('-')}>-</button>
            </td>
          </tr>
          <tr>
            <td>
              <button onClick={() => clickCommand('0')}>0</button>
            </td>
            <td>
              <button onClick={() => clickCommand('.')}>.</button>
            </td>
            <td>
              <button onClick={() => clickCommand('=')}>=</button>
            </td>
            <td>
              <button onClick={() => clickCommand('+')}>+</button>
            </td>
          </tr>
          </tbody>

        </table>
     
    </>
  )
}

export default App
